package com.demo;

/*
读写锁，读写分开两把锁，任一线程进行写操作时，其他线程不能进行任何操作，
而没有任何线程进行写操作时，所有线程可以同时读取数据，既保证了线程安全，
又能保证只是单纯读取数据时可以多线程并发，提供效率
 */

import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

class Demo9Counter {
    private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    private final Lock readLock = lock.readLock();
    private final Lock writeLock = lock.writeLock();
    private int count;

    public void add() {
        writeLock.lock();
        try {
            this.count++;
        } finally {
            writeLock.unlock();
        }

    }

    public int get() {
        readLock.lock();
        try {
            return this.count;
        } finally {
            readLock.unlock();
        }
    }
}
public class Demo9 {
    public static void main(String[] args) throws InterruptedException {
        Demo9Counter demo9Counter = new Demo9Counter();
        new Thread(() -> {
            demo9Counter.add();
        }).start();
        new Thread(() -> {
            demo9Counter.add();
        }).start();
        new Thread(() -> {
            demo9Counter.add();
        }).start();
        Thread.sleep(1000);
        System.out.println(demo9Counter.get());
        System.out.println(demo9Counter.get());
        System.out.println(demo9Counter.get());
        System.out.println(demo9Counter.get());
        System.out.println(demo9Counter.get());
    }
}
